<script setup>
import { artEditChannelService, artAddChannelService } from '@/api/article.js'
import { ref } from 'vue'

const dialogVisible = ref(false)
const formRef = ref()
const formModel = ref({
  cate_name: '',
  cate_alias: ''
})

const open = (row) => {
  // console.log(row)
  dialogVisible.value = true
  // 存在争议
  // formModel.value = row
  formModel.value = { ...row }
}
// 对外暴露方法
defineExpose({
  open
})

const emit = defineEmits(['success'])
const onSubmit = async () => {
  // 表单预检验
  formRef.value.validate()

  // 用isEdit判断是编辑还是添加
  const isEdit = formModel.value.id
  if (isEdit) {
    // 存在id就是编辑
    await artEditChannelService(formModel.value)
    ElMessage.success('编辑完成')
  } else {
    await artAddChannelService(formModel.value)
    ElMessage.success('添加成功')
  }
  // 不管是编辑还是增加,提交完都要关掉
  dialogVisible.value = false
  emit('success')
}

const rules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { pattern: /^\S{1,10}$/, message: '必须为1-10位字符', trigger: 'blur' }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    { pattern: /^[a-zA-Z]{1,10}$/, message: '必须为1-10为字母' }
  ]
}
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑类' : '增加分类'"
    width="30%"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 40px"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input
          v-model="formModel.cate_name"
          placeholder="请输入分类名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input
          v-model="formModel.cate_alias"
          placeholder="请输入分类别名"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
